package cn.wolfcode.rbac.service.system_manage.impl;


import cn.wolfcode.rbac.domain.Role;
import cn.wolfcode.rbac.mapper.system_manage.RoleMapper;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.system_manage.IRoleService;
import cn.wolfcode.rbac.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @version 1.0
 * @Author:Cao Zhijian
 * @DATE:2020/12/24 0024 14:40:32
 */

@Service
public class IRoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void delete(Long id) {
        roleMapper.deleteByPrimaryKey(id);

        // 删除关系表中的数据
        roleMapper.deleteRoleAndPermissionRelation(id);
    }

    @Override
    public Role get(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> listAll() {
        return roleMapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject queryObject) {

        int count = roleMapper.selectForCount();

        if(count == 0){
            // 1.如果数据库中没有数据是不需要分页显示，直接返回一个空数据
            return new PageResult(1,3,Collections.emptyList(),0);
        }else {
            // 2.如果数据库中有数据就要分页显示
            List<Role> roles = roleMapper.selectForList(queryObject);
            return new PageResult(queryObject.getCurrentPage(),queryObject.getPageSize(),roles,count);
        }
    }

    @Override
    public void saveOrUpdate(Role role,Long[] ids) {
        if(role.getId() == null){
            roleMapper.insert(role);
        }else {
            roleMapper.updateByPrimaryKey(role);
            roleMapper.deleteRoleAndPermissionRelation(role.getId());
        }

        if(ids !=null && ids.length>0){
            for(Long permissionId : ids){
                roleMapper.insertRoleAndPermissionRelation(role.getId(),permissionId);
            }
        }
    }
}
